#include "../common/common.h"
#include "../common/global.h"
#include "../renderer/renderer.h"
#include "../game/game.h"
#include "../ui/ui.h"

#include "cl_console.h"
#include "cl_sound.h"
#include "cl_input.h"
#include "client.h"

#include <SDL/SDL.h>

//鼠标指针在地图中的位置
int cursor_x;
int cursor_y;

static void loop_event(void)
{
	event_t * ev;
	while ((ev = com_get_event()) != NULL) {
		switch (ev->type) {
			case EV_KEY:
				cl_key_event(ev->key, ev->down);
				break;
			case EV_MOUSE_POS:
				cl_mouse_event(ev->x, ev->y, ev->time);
				break;
			case EV_MOUSE_REL:
				mouse_rel_x = ev->x;
				mouse_rel_y = ev->y;
				break;
			case EV_NONE:
			default:
				com_error("unknow event happend");
				break;
		}
	}

	cursor_x = mouse_pos_x + rd.camera.x;
	cursor_y = mouse_pos_y + rd.camera.y;
}

static enum {
	CL_QUIT,
	CL_PAUSE,
	CL_GAMING,
} cl_state = CL_GAMING;

void cl_update(void)
{
	player_t * p = &game.player[0];

	if (key_str_is_down("MOUSE2")) {
		p->dist_x = cursor_x;
		p->dist_y = cursor_y;
		rd.camera_locked = true;
	} else {
		rd.camera_locked = false;
	}

	if (key_str_is_down("ESCAPE")) {
		cl_state = CL_QUIT;
	}

	if (key_str_is_down("F12")) {
		rd_toggle_fullscreen();
	}
}

void cl_frame(void)
{
	loop_event();

	switch (cl_state) {
		case CL_GAMING:
			cl_update();
			g_update();
			break;
		case CL_PAUSE:
			g_pause();
			ui_menu();
			break;
		case CL_QUIT:
			com_quit(0);
			break;
		default:
			break;
	}

	cl_display();
}

void init_client(void)
{
	if (SDL_Init(SDL_INIT_EVERYTHING) == -1)
		com_fatal("SDL_Init");

	SDL_WM_SetCaption("我是中国人a！", NULL);

	init_renderer();
	init_sound();
	init_console();
	init_ui();
	init_game();

	cl_debug(" ");//初始化debug信息
}

void release_client(void)
{
	release_renderer();
	release_sound();
	release_console();
	release_ui();
	release_game();

	SDL_Quit();
}

void cl_pause(void)
{
	cl_state = CL_PAUSE;
}

void cl_unpause(void)
{
	cl_state = CL_GAMING;
}
